package com.xxxx.mail;

import com.rabbitmq.client.Channel;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.MailConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
/**
 * 消息接收者
 *
 * @author zhoubin
 * @since 1.0.0
 */
@Component
public class MailReceiver {
    private static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);
    // java邮件的发送
    @Autowired
    private JavaMailSender javaMailSender;
    // java邮件的配置
    @Autowired
    private MailProperties mailProperties;
    // 用这个模板传递给template
    @Autowired
    private TemplateEngine templateEngine;
    /*将信息传到redis中*/
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 邮件发送
     * @param message
     * @param channel
     * queue = mail.queue
     *
     * 注解的作用是：监听器
     */
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) {
        /**
         * 通过RabbitMQ获取到员工的信息
         * 第一步：获取员工信息
         */
        Employee employee = (Employee) message.getPayload();

        MessageHeaders headers = message.getHeaders();
        //消息序号
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String)headers.get("spring_returned_message_correlation");
        HashOperations hashOperations = redisTemplate.opsForHash();
        try {
            //判断redis的k为mail_log的表中 有没有这个Key为：MsgID的记录
            if (hashOperations.entries("mail_log").containsKey(msgId)) {
                //redis中包含key，说明消息已经被消费
                logger.info("消息已经被消费=====>{}", msgId);
                /**
                 * 手动确认消息
                 * tag:消息序号
                 * multiple:是否多条
                 */
                channel.basicAck(tag, false);
                return;
            }
            MimeMessage msg = javaMailSender.createMimeMessage();
            // 第一步：配置邮件发送的信息
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            //发件人
            helper.setFrom(mailProperties.getUsername());
            //收件人
            helper.setTo(employee.getEmail());
            //主题
            helper.setSubject("入职欢迎邮件");
            //发送日期
            helper.setSentDate(new Date());

            //第二步： 准备邮件中的内容 org.thymeleaf.context
            Context context = new Context();
            // 名字、职位、职称等这些员工的信息，是通过RabbitMQ来获取到的
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            // 将邮件内容和模板，融合在一起。
            // “mail"是模板，contex是内容。
            // 所以说：模板和内容相互融合==》就等于邮件内容
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            //第三步： 发送邮件
            javaMailSender.send(msg);
            logger.info("邮件发送成功");

            //将消息id存入
            hashOperations.put("mail_log",msgId,"OK");
            //手动确认消息
            channel.basicAck(tag,false);
        } catch (Exception e) {
            try {
                /**
                 * 手动确认消息
                 * tag:消息序号
                 * multiple:是否多条
                 * requeue:是否回退到队列
                 */
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                // 邮件发送失败，打印一下失败的原因
                logger.error("消息确认失败=====>{}", ex.getMessage());
            }
            logger.error("邮件发送失败=====>{}", e.getMessage());
        }
    }
}

    /*接受员工类：则不采取消费端幂等性操作
    public void handler(Employee employee){
        //创建消息
        MimeMessage msg = javaMailSender.createMimeMessage();
        System.out.println("创建消息：====》"+msg);

        //
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            //发件人
            helper.setFrom(mailProperties.getUsername());
            //收件人
            helper.setTo(employee.getEmail());
            //主题
            helper.setSubject("入职欢迎邮件");
            //发送日期
            helper.setSentDate(new Date());
            //邮件内容
            Context context= new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJoblevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            //templateEngine会从context拿相应的数据。（从context拿到相应内容，放到mail）
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);

            //发送邮件
            javaMailSender.send(msg);
        } catch (MessagingException e) {
            LOGGER.error("邮件发送失败=====>{}", e.getMessage());
        }
    }*/


